#!/usr/bin/env python
# -*- coding:utf8 -*-
# uncompyle6 version 2.15.1
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.10 (default, Jul  1 2017, 13:36:56) 
# [GCC 4.4.6 20110731 (Red Hat 4.4.6-4)]
# Embedded file name: ./esb/components/bk/apis/job/fast_execute_script.py
# Compiled at: 2017-11-16 15:44:28
"""
Tencent is pleased to support the open source community by making 蓝鲸智云(BlueKing) available.
Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and limitations under the License.
"""
from django import forms
from common.forms import BaseComponentForm, TypeCheckField
from components.component import Component
from common.constants import API_TYPE_OP
from .toolkit import tools, configs

class FastExecuteScript(Component):
    """
    apiLabel 快速执行脚本
    apiMethod POST
    
    ### 功能描述
    
    快速执行脚本
    
    ### 请求参数
    
    {{ common_args_desc }}
    
    #### 接口参数
    
    | 字段          |  类型      | 必选   |  描述      |
    |---------------|------------|--------|------------|
    | app_id        |  int       | 是     | 业务ID |
    | content       |  string    | 是     | 执行脚本步骤的脚本内容，base64编码后的内容 |
    | script_timeout|  int       | 否     | 脚本执行超时时间，范围60~72000，默认1000, 单位为秒 |
    | script_param  |  string    | 否     | 脚本执行参数 |
    | type          |  int       | 是     | 脚本类型：1(shell脚本)、2(bat脚本)、3(perl脚本)、4(python脚本)、5(Powershell脚本) |
    | ip_list       |  array     | 否     | 目标机器，包含内容见下面描述 |
    | server_set_id |  int       | 否     | 目标机器分组ID；server_set_id和ip_list至少一个必须存在，如果同时存在，则以server_set_id为准 |
    | account       |  string    | 是     | 目标机器账户名 |
    | is_param_sensitive |  int  | 是     | 是否敏感参数: 1是, 0不是(默认为0) |
    
    #### ip_list
    
    | 字段      |  类型      | 必选   |  描述      |
    |-----------|------------|--------|------------|
    | ip        |  string    | 是     | IP地址 |
    | source    |  int       | 是     | 子网ID |
    
    ### 请求参数示例
    
    ```python
    {
        "app_code": "esb_test",
        "app_secret": "xxx",
        "bk_token": "xxx",
        "app_id": 1,
        "content": "xxx",
        "ip_list": [
            {
                "ip": "10.0.0.1",
                "source": 1
            }
        ],
        "type": 1,
        "account": "root",
    }
    ```
    
    ### 返回结果示例
    
    ```python
    {
        "result": true,
        "code": "00",
        "message": "",
        "data": {
            "taskInstanceName": "API执行脚本1456715609220",
            "taskInstanceId": 10000
        },
    }
    ```
    """
    sys_name = configs.SYSTEM_NAME
    api_type = API_TYPE_OP
    host = configs.host

    class Form(BaseComponentForm):
        app_id = forms.IntegerField(label=u'业务ID', required=True)
        content = forms.CharField(label=u'脚本内容', required=True)
        script_timeout = forms.IntegerField(label=u'脚本执行超时时间', required=False)
        script_param = forms.CharField(label=u'脚本执行参数', required=False)
        type = forms.IntegerField(label=u'脚本类型', required=True)
        ip_list = TypeCheckField(label=u'目标机器', promise_type=list, required=False)
        server_set_id = forms.IntegerField(label=u'目标机器分组ID', required=False)
        account = forms.CharField(label=u'目标机器账户名', required=True)
        is_param_sensitive = forms.IntegerField(label=u'是否敏感参数', required=False)

        def clean(self):
            data = self.cleaned_data
            ip_list = [ FastExecuteScript.HostForm(ip).get_cleaned_data_or_error() for ip in data['ip_list']
                      ]
            params = {'applicationId': data['app_id'],
               'content': data['content'],
               'scriptTimeout': 1000 if data['script_timeout'] is None else data['script_timeout'],
               'scriptParam': data['script_param'],
               'type': data['type'],
               'account': data['account']
               }
            if data['is_param_sensitive'] is not None:
                params['isParamSensitive'] = data['is_param_sensitive']
            if data['server_set_id'] is not None:
                params.update(serverSetId=data['server_set_id'])
            else:
                if ip_list:
                    params.update(ipList=ip_list)
                else:
                    raise forms.ValidationError(u'目标机器[ip_list]和目标机器分组ID[server_set_id]至少存在一个。')
            return params

    class HostForm(BaseComponentForm):
        ip = forms.CharField(label=u'IP地址', required=True)
        source = forms.IntegerField(label=u'子网ID', required=True)

        def clean(self):
            data = self.cleaned_data
            return {'ip': data['ip'],
               'source': data['source']
               }

    def handle(self):
        data = self.form_data
        data['starter'] = self.current_user.username
        client = tools.JOBClient(self.outgoing.http_client)
        params = tools.get_basic_json('fastExecuteScript', params=data)
        result = client.post(self.host, data=params)
        self.response.payload = result
